import axios from 'axios'
import qs from 'qs'
import {
	Notification,
	MessageBox,
	Message
} from 'element-ui'
import store from '@/store'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import {
	Loading
} from 'element-ui';
// 定义请求次数(用于判断请求是否已经全部响应)
let requestCount = 0;
let loading;
// (客户端请求前)显示loading
function showLoading() {
	if (requestCount === 0) {
		loading = Loading.service({
			lock: true,
			text: '正在加载',
			target: '.sub-main',
			body: true,
			spinner: "el-icon-loading", //loading样式类名
			background: "rgba(0,0,0,0.8)"
		})
	}
	requestCount++
}
let timer;
// (服务器响应后)尝试隐藏loading
function tryHideLoading() {
	requestCount--
	//采用setTimeout是为了解决一个请求结束后紧接着有另一请求发起导致loading闪烁的问题
	timer = setTimeout(() => {
		if (requestCount === 0) {
			loading.close()
			clearTimeout(timer)
		}
	})
}
// axios.defaults.headers['Content-Type'] = 'text/plain'
// 创建axios实例
const service = axios.create({
	// axios中请求配置有baseURL选项，表示请求URL公共部分
	baseURL: 'https://zyne.com.cn:666/', //服务器
	//baseURL: 'http://192.168.15.117:9949/',//江权
	//baseURL: 'http://192.168.15.69:9949/',//本机
	// 超时
	timeout: 100000
})
// request拦截器
service.interceptors.request.use(config => {
	config.headers['Content-Type'] = 'application/json'
	config.headers['Accept'] = 'application/json'
	// config.headers['Access-Control-Allow-Origin']='*'
	//showLoading()
	if (config.method === 'post') { // post请求时，处理数据
		//console.log("请求------------")
		config.params = config.params
	}
	return config
}, error => {
	console.log(error)
	Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
		tryHideLoading()
		if (res.data.code != 1) {

			if (res.data.code == -2) {
				// store.dispatch('LogOut').then(() => {
				// 	location.reload() // 为了重新实例化vue-router对象 避免bug
				// })
			}
			// Message({
			// 	message: res.data.msg,
			// 	type: 'error',
			// 	duration: 5 * 1000
			// })


		}
		return res.data;
	},
	error => {
		tryHideLoading()
		//console.log('err' + error)
		let {
			message
		} = error;
		if (message == "Network Error") {
			//message = "后端接口连接异常";
		} else if (message.includes("timeout")) {
			//message = "系统接口请求超时";
		} else if (message.includes("Request failed with status code")) {
			//message = "系统接口" + message.substr(message.length - 3) + "异常";
		}
		// Message({
		// 	message: message,
		// 	type: 'error',
		// 	duration: 5 * 1000
		// })
		return Promise.reject(error)
	}
)

export default service
